package com.site.core.translate;

import java.util.HashMap;
import java.util.Map;
 
import com.cnc.bas.util.Log;
import com.google.api.translate.Translate;
import com.site.common.Language;


public class GoogleTranslate {
	
	protected static Log  log = Log.getLogger(GoogleTranslate.class);
	
	// 语言映射
	private static Map<String, com.google.api.translate.Language> map = new HashMap<String, com.google.api.translate.Language>();
	
	static{
		init();
	}
	
	 /**
     * 翻译
     */
    public String translate(String content, String fromLang, String toLang) {
		return googleTranslate(content, map.get(fromLang), map.get(toLang));
	}

    /**
     * google 翻译接口
     * @param content
     * @return
     */
    private static String googleTranslate(String content, com.google.api.translate.Language from, com.google.api.translate.Language to) {
        Translate.setHttpReferrer("http://www.heie.com");
        for(int i=0; i<3; i++){
        	 try {
                 String translatedText = Translate.execute(content, from, to);
                 return translatedText;
             }
             catch (Exception e) {
                log.logError("translate exception:" + e.getMessage());
             }
             try{
             	Thread.sleep(3000);
             }
             catch(Exception e){
             }
        }
       
        return "";
    }
    
    /**
     * 初始化语言映射
     */
    private static void init(){
		map.put(Language.CHINESE_SIMPLIFIED, com.google.api.translate.Language.CHINESE_SIMPLIFIED);
		map.put(Language.ENGLISH, com.google.api.translate.Language.ENGLISH);
		map.put(Language.SPANISH, com.google.api.translate.Language.SPANISH);
		map.put(Language.PORTUGUESE, com.google.api.translate.Language.PORTUGUESE);
		map.put(Language.JAPANESE, com.google.api.translate.Language.JAPANESE);
		map.put(Language.GERMAN, com.google.api.translate.Language.GERMAN);
		map.put(Language.FRENCH, com.google.api.translate.Language.FRENCH);
	}

   
}

